<?php

namespace App\Console\Commands\Corn;

use App\Models\Owner;
use App\Services\EstateService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CloseOwner extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'corn:close-owner';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '关闭合同';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Owner::query()->where('will_close', true)->get()->each(function ($owner) {

            // 判断是否为最后一期 同时 判断当前合同是否结束
            if ($owner->lastItem->count == $owner->items->count() && \Illuminate\Support\Carbon::now()->gte($owner->ended_at)) {
                //合同关闭
                $owner->will_close = false;
                $owner->closed = true;
                $owner->save();

                // 解除合同和房间的依赖，把房间设置为可以出租
                (new EstateService())->changeIsRent($owner);
            } else {
                Log::error("代码异常：当前合同不是最后一期的账单，但是will_close却为true");
            }

        });
    }
}
